<template>
    <div class="todo-list">
        <header>
            <input type="checkbox" :checked="checkAll" @change="toggleAll(!checkAll)">全选
            <input type="text" placeholder="请输入待办事项" @keyup.enter="addTodo">
        </header>
        <div class="con">
            <h1>列表</h1>
            <ul>
                <todo-item v-for="(todo,ind) in filterTodos" :key="ind"
                    :todo="todo"
                ></todo-item>
            </ul>
        </div>
        <footer>
            <h1>未完成的事项数量：{{notDoneCount}}</h1>
            <div>
                <span @click="visibility = key" 
                style="padding:0 10px;" 
                v-for="(item,key,ind) in filters" 
                :key="ind">{{key}}</span>
            </div>
        </footer>
    </div>
</template>
<script>
import todoItem from '../components/todoItem'
import {mapActions,mapGetters} from 'vuex'

export default {
    data(){
        return {
            visibility:'all',
            filters:{
                'all':todos => todos,
                'completed':todos => todos.filter(item => item.done),
                'active':todos => todos.filter(item => !item.done)
            }
        }
    },
    components:{
        todoItem
    },
    computed:{
        todos(){
            return this.$store.state.todos
        },
        checkAll(){
            return this.todos.length && this.todos.every(item => item.done)
        },
        ...mapGetters(['notDoneCount']),
        filterTodos(){
            return this.filters[this.visibility](this.todos)
        }
    },
    methods:{
        addTodo(e){
            let val = e.target.value.trim();
            this.$store.dispatch('addTodo',val); 
        },
        ...mapActions(['toggleAll'])
    }
}
</script>
